
# coding:utf-8
# https://zhidao.baidu.com/question/1962944875089827980.html
import re
from strUtil.strUtil import sub_strs_start_end_all
from strUtil.strUtil import front_del_str
from strUtil.strUtil import r_del_str

from xml.dom import minidom


class Question:
    def __init__(self, queText, queNum, options, right=False):
        self.queText = queText
        self.queNum = queNum
        self.options = options
        self.right = right


# 读取xml文档的方法
# http://yshblog.com/blog/42
def read_my_try_xml(filename):
    # 打开这个文档，用parse方法解析
    xml = minidom.parse(filename)
    # xml.getElementsByTagName()
    main = xml.getElementsByTagName("main")[0]
    title = main.getElementsByTagName("title")[0].childNodes[0].data
    description = main.getElementsByTagName("description")[0].childNodes[0].data
    ques = main.getElementsByTagName("oneQues")
    questions = []
    for que in ques:
        type = que.getAttribute('type')

        # print("type:", type)
        queNum = que.getElementsByTagName("queNum")[0]
        question = que.getElementsByTagName("question")[0]
        select = que.getElementsByTagName("select")[0]
        options = que.getElementsByTagName("option")

        questions.append(get_one_que(options))

    # print("questions:", questions)
    return title, description, questions


def get_one_que(options):
    one_que = []
    for option in options:
        nodeName = option.nodeName
        # print("nodeName:", nodeName)
        isChosen = option.getElementsByTagName("choose")[0].childNodes[0].data
        # print("isChosen:" + isChosen)
        optionText = option.childNodes[0].data.strip()
        if isChosen == "true":
            optionText += " :你选择了他"
        # print("optionText:", optionText)
        # if isChosen=="true":
        one_que.append(optionText)
    return one_que


def bb_questions_by_file():
    # todo
    pass


def bbQuestions(score_data, xml_filename):
    title, description, questions = read_my_try_xml(filename=xml_filename)
    # quesList=re.findall(r'(问题.*。)',score_data)
    out_data = f"标题: {title}\n"
    out_data += "描述: " + description + "\n"

    quesList = sub_strs_start_end_all(score_data, "问题", "。")
    for que in quesList:
        queNum, score, queText = split_a_que_paragraph(que)
        out_data += "题号: " + str(queNum) + "\n"
        out_data += "分数: " + str(score) + "\n"
        out_data += "问题: " + queText + "\n"
        out_data = pushOptions(out_data, questions[queNum - 1])
        out_data += "----------------------------------\n\n"

    filename = r_del_str(xml_filename, ".xml")
    file_out = open(filename + ".txt", "w", encoding="utf-8")

    file_out.write(out_data)
    file_out.close()


def write_bb_questions(score_data: str, try_filename, debug=False):
    # title, description, questions = read_my_try_xml(filename=xml_filename)
    # quesList=re.findall(r'(问题.*。)',score_data)
    # title_pos=score_data.find("标题")
    # if(title_pos==-1):
    #     # out_data = f"标题: {title}\n"
    #     ret_pos=score_data.find("\n",out_data)
    #     out_data=score_data[title_pos:ret_pos]
    # out_data = f"标题: {title}\n"
    # out_data += "描述: " + description + "\n"
    if score_data.endswith(".txt"):
        file_score_data = open(score_data, "r", encoding="utf-8")
        score_data = file_score_data.read()
        file_score_data.close()
    pos_before_que = score_data.find("问题")
    out_data = score_data[:pos_before_que]
    file_try = open(try_filename, "r", encoding="utf-8")
    try_data = file_try.read()
    file_try.close()
    quesList = sub_strs_start_end_all(score_data, "问题", "-----------------")
    try_list = sub_strs_start_end_all(try_data, "问题", "-------------------------------")
    now_num = 0
    for que in quesList:
        queNum, scoreStr, queText = split_a_que_paragraph(que)
        now_try_str = try_list[now_num]
        now_try_str = now_try_str.replace("-------------------------------", "")
        now_try_str += "\n分数: " + scoreStr + "\n-------------------------------\n"
        now_num += 1
    for one_que in quesList:
        out_data += one_que
        # queNum, scoreStr, queText = split_a_que_paragraph(que)
        # out_data += "题号: " + str(queNum) + "\n"
        # out_data += "分数: " +scoreStr + "\n"
        # out_data += "问题: " + queText + "\n"
        # out_data = pushOptions(out_data, questions[queNum - 1])
        # out_data+="----------------------------------\n\n"
    if (not debug):
        filename = r_del_str(try_filename, ".txt")
        file_out = open(filename + "_with_score" + ".txt", "w", encoding="utf-8")

        file_out.write(out_data)
        file_out.close()


def pushOptions(out_data, options):
    out_data += "选项: \n"
    for option in options:
        out_data += option + "\n"
    return out_data


def getScore(score_str: str):
    de_pos = score_str.find("得")
    fen_pos = score_str.find("分")
    return float(score_str[de_pos + 2:fen_pos])


def split_a_que_paragraph(paragraph: str):
    parts = paragraph.split("\n")
    parts.remove("")
    queNum = int(parts[0].replace("问题 ", ""))
    # score = getScore(parts[1])
    scoreStr = (parts[1])
    queText = parts[2]
    return queNum, scoreStr, queText


import json

# https://www.runoob.com/python/python-json.html

import ast
import os


def put_score_to_record(record_filename, score_filename, out_dir):
    record_file = open(record_filename, "r", encoding="utf-8")
    record_data = record_file.read()
    record_file.close()
    score_file = open(score_filename, "r", encoding="utf-8")
    score_data = score_file.read()
    score_file.close()
    # print("record_data: ",record_data)
    dic_record = record_data
    # dic_record = ast.literal_eval(record_data.strip())
    # scores=ast.literal_eval(score_data)
    dic_record = json.loads(record_data)
    scores = score_data
    scores = json.loads(score_data)
    # print("dic_record:",dic_record)
    questions = dic_record["questions"]
    cnt = 0
    for question in questions:
        score_str = scores[cnt].strip()
        question["score_str"] = score_str
        question["score"] = getScore(score_str)
        cnt += 1

    # print("questions:",questions)
    print("dic_record:", dic_record)
    # title = "cs_principle_experiment"
    title=to_file_path_name(dic_record["title"])
    out_filename = os.path.join(out_dir, "bb_with_score_" + title + ".json")
    if os.path.exists(out_filename):
        print("exists",out_filename)
    else:
        out_file = open(out_filename, "w")
        # str(dic_record)
        out_file.write(json.dumps(dic_record))

        out_file.close()
        print("put at", out_filename)
    # out_data= json.dumps(dic_record)


def read_dic(json_filename):
    file = open(json_filename, "r", encoding="utf-8")
    file_data = file.read()
    file.close()
    return json.loads(file_data)


def writeObjToTxtAndDownload(totalObj, has_score, out_dir):
    # console.log("writeObjToTxtAndDownload");
    # debug = debug || false;
    title = totalObj["title"]
    outTxt = "标题: " + title + "\n"
    outTxt += "描述: " + totalObj["description"] + "\n"
    questions = totalObj["questions"]
    # // console.log("questions.length:"+questions.length);

    # // oneQueAnswersObj={
    #                     //     type:"choose",
    # //     answers:answers
    #                // };
    cnt = 1
    for question in questions:
        outTxt += f"题号: {cnt}\n"
        if has_score:
            outTxt += f"分数: {question['score_str']}\n"
        outTxt += f"问题: {question['que']}\n"
        outTxt += "你的答案:\n"
        answers = question["answers"]["answers"]
        outTxt = pushAnswersToOutTxt(outTxt, answers, question["answers"]["type"])
        outTxt += "---------------------------------------------------------------------------------------------------------\n\n"
        cnt += 1

    # print("outTxt", outTxt)
    # print(question)
    title = title.replace(" ", "_")
    # https://www.cnblogs.com/jjliu/p/11514226.html
    title = title.replace(":", "")
    print(title)
    out_filename = os.path.join(out_dir, "bb_with_score_" + title + ".txt")
    print("out_filename:", out_filename)
    if os.path.exists(out_filename):
        print("exists", out_filename)
    else:
        out_file = open(out_filename, "w", encoding="utf-8")
        out_file.write(outTxt)
        out_file.close()


def to_file_path_name(filename:str):
    filename=filename.strip()
    filename = filename.replace(" ", "_")
    # https://www.cnblogs.com/jjliu/p/11514226.html
    filename = filename.replace(":", "")
    return filename


def pushAnswersToOutTxt(outTxt, answers, type):
    cnt = 1
    for answer in answers:
        outTxt += f"{cnt}、   "
        if (type == "choose"):
            outTxt += answer["text"]
            outTxt += "    :你选择了他" if answer["chosen"] else ""
        else:
            outTxt += answer
        outTxt += "\n"
        cnt += 1

    return outTxt


if __name__ == '__main__':
    # read_my_try_xml(r"E:\Download\bb_202计算机系统原理_执行测验_ Test1 计算机系统概论 (1).xml")
    # bbQuestions(score_data)
    # bbQuestions(score_data=score_data, xml_filename=r"E:\Download\bb_202计算机系统原理_执行测验_ Test1 计算机系统概论 (1).xml")
    # write_bb_questions(score_data="score_data.txt",
    #                    try_filename=r"E:\Download\bb_202计算机系统原理_执行测验_ 第2章 数据表示与处理一 (1) - 副本.txt",debug=False)

    # data = int(input())
    # a = [1,3,5,7,9]
    # a.append(6)
    # a.sort()
    # print(a)
    # put_score_to_record(record_filename=r"E:\download2\bb_执行测验_ listening 2.json"
    #                     ,score_filename=r"E:\download2\bb_score_复查测验提交_ listening 2.json",
    #                     out_dir=r"e:\file\学校\英语")

    dic = read_dic(r"e:\file\学校\英语\bb_with_score_执行测验_listening_2.json")
    
    writeObjToTxtAndDownload(dic, True, out_dir=r"E:\file\学校\英语\bb")
